package org.voice;

import org.vosk.*;
import javax.sound.sampled.*;

public class VoskRealtimeSpeechToText {

    public static void main(String[] args) {
        // 初始化 Vosk 库
//        String modelPath = "D:\\model\\vosk-model-cn-0.22";
        String modelPath = "D:\\model\\vosk-model-small-cn-0.22";
//        MyTTS tts = new MyTTS();
        try (Model model = new Model(modelPath)) {
            // 配置音频格式
            AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

            // 检查系统是否支持该音频格式
            if (!AudioSystem.isLineSupported(info)) {
                System.out.println("不支持该音频格式");
                return;
            }

            // 打开音频输入
            try (TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info)) {
                line.open(format);
                line.start();

                // 创建 Vosk 识别器
                try (Recognizer recognizer = new Recognizer(model, 16000)) {
                    byte[] buffer = new byte[4096];
//                    new MyTTS().say("开始录音，请说话...");
                    while (true) {
                        int bytesRead = line.read(buffer, 0, buffer.length);
                        if (bytesRead > 0) {
                            if (recognizer.acceptWaveForm(buffer, bytesRead)) {
                                String result = recognizer.getResult();
                                System.out.println(result);
                            }
                        }
                    }
                }
            } catch (LineUnavailableException e) {
                System.out.println("无法打开音频输入: " + e.getMessage());
            }
        } catch (Exception e) {
            System.out.println("发生错误: " + e.getMessage());
        }
    }
}
